package cn.com.cninfo.servlet;


import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import java.io.IOException;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by liuhuan on 2016/7/11.
 */
public class CADemoServlet extends HttpServlet {

    private final String externRegion = "1.2.86.100.4.5.1";

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        X509Certificate[] ca = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");
        X509Certificate x509 = ca[0];

        Map<String, Object> result = new HashMap<String, Object>();
        try {
            x509.checkValidity();
        } catch (CertificateExpiredException e) {
            result.put("error", "证书已过期！");
            response.getWriter().printf(JSON.toJSONString(result));
            return;
        } catch (CertificateNotYetValidException e) {
            result.put("error", "证书不可用！");
            response.getWriter().printf(JSON.toJSONString(result));
            return;
        }

        result.put("serialNumber", x509.getSerialNumber().toString());
        result.put("signature", x509.getSignature().toString());
        result.put("oid", x509.getSigAlgOID());
        result.put("issuerName", x509.getIssuerX500Principal().getName());
        result.put("subjectName", x509.getSubjectX500Principal().toString());
        result.put("orgCode", new String(x509.getExtensionValue(externRegion)).substring(4));

        response.getWriter().printf(JSON.toJSONString(result));
    }

}
